import 'package:gold/base/config.dart';
import 'package:gold/base/view_model.dart';
import 'package:gold/http/api_order.dart';
import 'package:gold/http/http.dart';
import 'package:gold/model/order_model.dart';
import 'package:gold/route/routes.dart';
import 'package:gold/route/xfg_nav.dart';
import 'package:gold/utils/xfg_extension.dart';

/// @description:
/// @author tangzhentao
/// @created at 22:50 2025/2/28

class OrderDetailViewmodel extends Viewmodel {
  /// 商品类型
  final String orderType;
  /// 订单id
  final int orderId;

  /// 订单信息
  OrderModel? order;

  OrderDetailViewmodel(this.orderType, this.orderId);

  /// 加载数据
  Future load() async {
    setLoading();
    final result = await Http().request<OrderModel>(ApiOrder.detail, showErrorMsg: false, data: {'id': orderId});
    if (result.success) {
      order = result.data;
      if (order != null) {
        setSuccess();
      } else {
        setEmpty(msg: '未获取到订单信息');
      }
    } else {
      setFailed(msg: result.msg);
    }
  }

  /// 查看物流
  Future checkLogistics() async {
    final expressDetail = order?.express?.expressDetail;
    if (expressDetail != null && expressDetail.status != null && expressDetail.status != 1 && order?.address != null && order?.detail?.product != null) {
      XfgNav.pushNamed(Routes.myOrderLogistics, arguments: {
        'product': order?.detail?.product!, 'address': order?.address!, 'express': expressDetail});
    } else {
      '物流/商品/地址信息异常'.info();
    }
  }

  /// 处理退款
  Future handleRefund() async {
    if (order?.refundStatus == RefundStatus.unApply) {
      XfgNav.pushNamed(Routes.myOrderApplyRefund, arguments: order!);
    } else {
      if (!_isValidOrder()) return;
      XfgNav.pushNamed(Routes.myOrderRefundApplying, arguments: {
        'orderId': order?.id, 'points': order?.pointsPrice?? 0,
        'price': (order?.payPrice?? 0.00) + (order?.amountNum?? 0.00),
        'productLogo' : order?.detail?.product?.coverImage, 'productName': order?.detail?.product?.name
      });
    }
  }

  /// 再次购买
  Future buyAgain() async {
    if (!_isValidProduct()) return;
    final productId = order!.detail!.productId!;
    if (orderType == ProductType.product) {
      XfgNav.pushNamed(Routes.goodsDetail, arguments: productId);
    } else if (orderType == ProductType.gold) {
      XfgNav.pushNamed(Routes.goldInvest, arguments: productId);
    } else {
      XfgNav.pushNamed(Routes.integralGoods, arguments: productId);
    }
  }

  /// 有效订单
  bool _isValidOrder() {
    final result = order?.id != null;
    if (!result) {
      '订单信息异常'.error();
    }
    return result;
  }

  /// 有效商品
  bool _isValidProduct() {
    final result = order?.detail?.productId != null;
    if (!result) {
      '商品信息异常'.error();
    }
    return result;
  }

  @override
  onRetry() => load();

  @override
  onReload() => load();
}
